package com.rockcent.wechat.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.RedPacket;
import com.rockcent.mall.lib.domain.RedPacketCoupon;
import com.rockcent.mall.lib.domain.enumclass.PacketCouponStatus;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.dto.RedPacketCouponDto;
import com.rockcent.mall.lib.repository.MerchantRepository;
import com.rockcent.mall.lib.repository.RedPacketCouponRepository;
import com.rockcent.mall.lib.repository.RedPacketRepository;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zhangjh on 2016/10/28.
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class RedPacketController extends BaseController {
    public static final Logger log = LoggerFactory.getLogger(RedPacketController.class);

    @Autowired
    private CustomerHelper customerHelper;
    @Autowired
    private RedPacketRepository redPacketRepository;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private RedPacketCouponRepository redPacketCouponRepository;

    /**
     * @api{post} /api/v2/red_packet/status 红包领取情况
     * @apiGroup redPacket
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} redPacketId 红包id
     * @apiParam {String} merchantId 红包id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "code": "1",
    "desc": "成功",
    "data": {
        "toked": [
            {
            "id": 1,
            "dateCreated": "2016-05-25 11:38:29",
            "lastUpdated": "2016-05-29 17:14:40",
            "couponName": "quan",
            "isShareReward": "NO",
            "redPacketId": 1,
            "customerHeadUrl": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLAk21s4ibg18hWV6Rf8UU1dkkIM2NXertjZUKLEWPkqn8cWNdyUIUuOHoB932EEpfZyNB4gHu7dmJQ/0",
            "remark": "满11减11",
            "couponType": "抵用券",
            "merchantName": "逗逼",
            "couponFaceValue": "11",
            "couponDiscount": "",
            "couponDateDisabled": "2016-05-25",
            "identifier": "33867d5b15ee3f7192af19b7df04fc0b",
            "logo": "http://upload.uat.rockcent.com/images/20160525/20160525111251TdrZdOOA.png"
            },
        ...
        ]
        "status": "已领取6/49"
        }
    }
     */
    @RequestMapping(value = Routes.RED_PACKET_STATUS, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult status(Long redPacketId, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (null == redPacketId){
                jr.remind("redPacketId is Null",log);
                return;
            }
            RedPacket redPacket = redPacketRepository.findByIdAndIsDelete(redPacketId, Whether.NO);
            if (redPacket == null){
                jr.errorParam("红包已经不存在了",log);
                return;
            }
            //查询已领取红包和总红包的数量
            List<RedPacketCouponDto> coupons = redPacketCouponRepository.findAllByRedPacketIdAndIsShareRewardAndStatus(redPacket.getId(),Whether.NO, PacketCouponStatus.TAKED);
            List<RedPacketCouponDto> allCoupons = redPacketCouponRepository.findAllByRedPacketIdAndIsShareRewardAndStatus(redPacket.getId(),Whether.NO, null);

            HashMap result = new HashMap<>();
            result.put("toked",coupons);
            result.put("status", "已领取" + coupons.size() + "/" + allCoupons.size());

            //名字、logo的默认值及对应的需要处理 TODO:后续处理两个字段的问题
            List list = new ArrayList();
            for (RedPacketCouponDto coupon : coupons) {

                HashMap couponDetail = new HashMap();
                couponDetail.put("couponName", coupon.getCouponName());
                couponDetail.put("takeDate", coupon.getLastUpdated());

                String nickName = "匿名";
                if (StringUtils.isNotBlank(coupon.getCouponName())) {
                    nickName = coupon.getCouponName();
                }
                String logo = null;
                //String logo = grailsApplication.config.asset.domain + "/images/none.jpg";
                if (StringUtils.isNotBlank(coupon.getCustomerHeadUrl())) {
                    logo = coupon.getCustomerHeadUrl();
                }

                jr.setData(result);
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api{get} /api/v1/red_packet/show 红包的基本信息
     * @apiGroup redPacket
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} redPacketId 红包id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "code": "1",
    "desc": "成功",
    "data": {
        "id": 1,
        "dateCreated": "2016-05-25 11:11:15",
        "lastUpdated": "2016-06-24 11:11:51",
        "version": 5,
        "adUrl": "",
        "dateDisabled": "2016-06-24 11:11:08",
        "dateEnabled": "2016-05-25 11:11:08",
        "dateStart": "2016-05-25 11:11:08",
        "identifier": "62bab84a1e628c63cf1a3fabe49c5e09",
        "intro": "点开有惊喜",
        "isShareReward": "YES",
        "isUnion": "NO",
        "merchantId": 2,
        "name": "  111",
        "status": "EXPIRED"
        }
    }
     */
    @RequestMapping(value = Routes.RED_PACKET_SHOW, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult get(Long redPacketId,HttpServletRequest request) {
        RestDoing doing = jr -> {
            if (null == redPacketId){
                jr.remind("redPacketId is Null",log);
                return;
            }
            RedPacket redPacket = redPacketRepository.findByIdAndIsDelete(redPacketId,Whether.NO);
            if(null == redPacket){
                jr.errorParam("红包已经不存在了",log);
                return;
            }
            jr.setData(redPacket);
        };
        return doing.go(request, log);
    }

    /**
     * @api{get} /api/v2/redPacket/luckyDraw 打开红包
     * @apiGroup redPacket
     * @apiParam {String} openId 用户open id
     * @apiParam {String} redPacketId 红包id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "msg": "success",
    "code": 200,
    "data": {
    "rewardCoupon": {
    "identifier": "9738da7853e4d68fc776ee49d16a5218",
    "openId": null,
    "name": "抵用券2"
    },
    "coupon": {
    "identifier": "6b1d1d611a444c3f88354d5bcaf96bb8",
    "couponDateDisabled": "2016-05-29",
    "dateCreated": "2016-05-29 14:43:10",
    "couponFaceValue": "",
    "couponType": "折扣券",
    "name": "折扣券2",
    "logo": "http://upload.dev.rockcent.com/images/20160529/20160529143720QvpcJCSP.jpg",
    "remark": "满100享8折"
    }
    }
    }
     */
    @RequestMapping(value = Routes.RED_PACKET_MY_RED_PACKET, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult myRedPacket(Long openId, Long redPacketId, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jr -> {
            if (null == redPacketId){
                jr.remind("redPacketId is Null",log);
                return;
            }
            RedPacket redPacket = redPacketRepository.findOne(redPacketId);
            if(null == redPacket){
                jr.errorParam("红包已经不存在了",log);
                return;
            }
            //判断红包是否被领取了，如果不领去，就往里面抽取卡券；领取了就返回红包里面的卡券
            List<RedPacketCouponDto> coupon = redPacketCouponRepository
                    .findAllByRedPacketIdAndIsShareRewardAndStatus(redPacket.getId(), Whether.NO, PacketCouponStatus.TAKED);
            if (null == coupon) {
                jr.remind("红包已经发完",log);
                return;
            }
            //TODO:2016/11/15
        };
        return doing.go(request, log);
    }

    //红包的校验
    private void vaildateRedPacket(RedPacket redPacket) {
        /*if (redPacket == null)
            throw new ValidateException("红包不存在")

        switch (redPacket.status) {
            case PacketStatus.DRAFT: throw new ValidateException("红包未发布")
            case PacketStatus.STOP: throw new ValidateException("红包已结束")
            case PacketStatus.EXPIRED: throw new ValidateException("红包已截止")
            case PacketStatus.FINISH: throw new ValidateException("红包已领完")
        }

        Date now = new Date()
        if (now.before(redPacket.dateStart))
            throw new ValidateException("红包未开始")

        if (now.after(redPacket.dateDisabled)) {
            redPacket.status = PacketStatus.EXPIRED
            redPacket.save(flush: true)
            throw new ValidateException("红包已结束")
        }*/
    }

}
